from nicegui import ui, app
import 数据, 镜像控制

app.add_static_files("/static", "static")

# 在全局样式中添加精确控制
ui.add_head_html(
    """
<style>
    html, body, .nicegui-content {
        margin: 0 !important;
        padding: 0 !important;
        height: 100% !important;
        width: 100% !important;
        overflow: hidden !important;
    }
    .bg-img {
        background-image: url(/static/bg.jpg);
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;
        # background-size: auto;
        # background-repeat: repeat;
        background-color: rgba(255, 255, 255, 0.25);
        background-blend-mode: lighten;
    }
</style>
"""
)


async def _快捷键(e):
    if 数据.比赛进行中() == False:
        return

    if e.action.keydown:
        if e.key == "ArrowUp":
            右边加分()
        elif e.key == "ArrowDown":
            右边减分()
        elif e.key == "ArrowLeft":
            左边减分()
        elif e.key == "ArrowRight":
            左边加分()
        elif e.key == "Escape":
            await 重新开始()
        elif e.key == " ":
            交换场地()
        elif e.key == "Enter":
            下一局()
        elif e.key == "h" or e.key == "H":
            await 帮助窗口()


ui_快捷键 = ui.keyboard(on_key=_快捷键, repeating=False, active=False)
ui_page = ui.element().classes("w-full h-screen")


def main():
    ui_main = ui.grid(columns="3fr 1fr 3fr").classes("w-full h-full p-4 bg-img")
    with ui_main:
        # logo
        ui.label("by fzqr100 2025-08").classes("m-2 text-gray-500").style(
            "position: absolute; top: 0; right: 0;"
        )

        # 比赛信息
        with ui.card().classes(
            "rounded-xl bg-gray-500 bg-opacity-20 items-center"
        ).style("position:absolute; top:10; left:50%; transform:translateX(-50%)"):
            ui.label(数据.显示比赛局数()).classes("text-h2 font-bold text-gray-700")
            ui.label(f"第{数据.当前局()}局").classes("text-h2 font-bold text-gray-700")

        ui_left = (
            ui.column().classes("items-center p-4").style("border-radius: 35px 0 0 0;")
        )
        ui_middle = ui.column().classes("items-center justify-center")
        ui_right = (
            ui.column().classes("items-center p-4").style("border-radius: 0 35px 0 0;")
        )

        # 左边选手区域
        with ui_left:
            with ui.card().classes("rounded-xl bg-gray-500 bg-opacity-20"), ui.row():
                # 选手名称
                ui.label(f"{数据.左边姓名()}").classes("text-h2 font-bold").style(
                    f"color: {数据.左边颜色()}"
                )
                # 局分
                ui.badge(f"{数据.左边胜局()}", color=f"{数据.左边颜色()}").classes(
                    "text-[56px] font-bold"
                )
            # 比分牌
            with ui.card().classes(
                f"w-full h-full rounded-[36px] bg-[{数据.左边颜色()}] bg-opacity-80"
            ):
                # ui.badge(f"{数据.左边胜局()}", color="gray").classes(
                #     "text-[128px] m-4"
                # ).style("position: absolute; top: 0; left: 0;")
                ui.label(f"{数据.左边状态()}").classes("text-h2 m-4").style(
                    "position: absolute; top: 0; right: 0;"
                )
                ui.label(数据.左边得分()).classes(
                    "w-full h-full text-h1 font-bold flex items-center justify-center"
                ).style("color: white; font-size: 55vh;")

        # VS分隔
        with ui_middle:
            ui.button("重新开始", on_click=重新开始).classes("w-24").props(
                "color=orange"
            )
            ui.button("交换场地", on_click=交换场地).classes("w-24").props(
                "color=green"
            )
            ui.button("下一局", on_click=下一局).classes("w-24").props("color=green")
            ui.button("? 帮助", on_click=帮助窗口).classes("w-24").props("color=green")
            ui.link("镜像控制", 镜像控制.p_mirror)
            ui.label()  # 空行
            with ui.row().classes("gap-4"):
                ui.button("+", on_click=左边加分).classes("w-10").classes(
                    f"!bg-[{数据.左边颜色()}]"
                )
                ui.button("+", on_click=右边加分).classes("w-10").classes(
                    f"!bg-[{数据.右边颜色()}]"
                )
            with ui.row().classes("gap-4"):
                ui.button("-", on_click=左边减分).classes("w-10").classes(
                    f"!bg-[{数据.左边颜色()}]"
                )
                ui.button("-", on_click=右边减分).classes("w-10").classes(
                    f"!bg-[{数据.右边颜色()}]"
                )

        # 右边选手区域
        with ui_right:
            with ui.card().classes("rounded-xl bg-gray-500 bg-opacity-20"), ui.row():
                # 选手名称
                ui.label(f"{数据.右边姓名()}").classes("text-h2 font-bold").style(
                    f"color: {数据.右边颜色()}"
                )
                # 局分
                ui.badge(f"{数据.右边胜局()}", color=f"{数据.右边颜色()}").classes(
                    "text-[56px] font-bold"
                )
            # 比分牌
            with ui.card().classes(
                f"w-full h-full rounded-[36px] bg-[{数据.右边颜色()}] bg-opacity-80"
            ):
                # ui.badge(f"{数据.右边胜局()}", color="gray").classes(
                #     "text-[128px] m-4"
                # ).style("position: absolute; top: 0; right: 0;")
                ui.label(f"{数据.右边状态()}").classes("text-h2 m-4").style(
                    "position: absolute; top: 0; left: 0;"
                )
                ui.label(数据.右边得分()).classes(
                    "w-full h-full text-h1 font-bold flex items-center justify-center"
                ).style("color: white; font-size: 55vh;")


def init():
    with ui.card().classes("m-4"):
        ui.label("乒乓球记分牌").classes("text-2xl")
        with ui.row():
            ui_选手1 = ui.input("选手1名称", value=数据.左边姓名())
            ui_选手2 = ui.input("选手2名称", value=数据.右边姓名())
        with ui.row():
            with ui.card():
                ui.label("比赛局数")
                ui_比赛局数 = ui.radio([1, 3, 5, 7], value=数据.比赛局数()).props(
                    "inline"
                )
            with ui.card():
                ui.label("起始发球权")
                ui_起始发球权 = ui.radio(
                    {1: "选手1", 2: "选手2"}, value=数据.起始发球权()
                ).props("inline")
        ui.button(
            "开始比赛",
            on_click=lambda: 开始比赛(
                ui_选手1.value, ui_选手2.value, ui_比赛局数.value, ui_起始发球权.value
            ),
        )


async def 帮助窗口():
    ui_快捷键.active = False
    # 创建对话框
    with ui.dialog() as dialog, ui.card().classes("w-64 fixed top-20"):
        ui.label("🟢 按钮快捷键说明").classes("text-h6")
        rows = [
            {"按钮": "重新开始", "快捷键": "【Esc】"},
            {"按钮": "交换场地", "快捷键": "【空格键】"},
            {"按钮": "下一局", "快捷键": "【回车键】"},
            {"按钮": "帮助", "快捷键": "【H】"},
            {"按钮": "左边加分", "快捷键": "【右箭头】"},
            {"按钮": "左边减分", "快捷键": "【左箭头】"},
            {"按钮": "右边加分", "快捷键": "【上箭头】"},
            {"按钮": "右边减分", "快捷键": "【下箭头】"},
        ]
        with ui.grid(columns=2).classes("pl-8"):
            for r in rows:
                ui.label(r["按钮"])
                ui.label(r["快捷键"])
        with ui.row().classes("w-full justify-center"):
            ui.button("确定", on_click=lambda: dialog.close())
    # 等待对话框关闭
    await dialog
    ui_快捷键.active = True


async def show_confirm(msg):
    # 创建对话框
    with ui.dialog() as dialog, ui.card().classes("fixed top-20"):
        ui.label(msg).classes("text-h6")
        # 创建事件用于返回结果
        result = False

        def set_result(value):
            nonlocal result
            result = value
            dialog.close()

        with ui.row().classes("w-full justify-center"):
            ui.button("取消", on_click=lambda: set_result(False))
            ui.button("确定", on_click=lambda: set_result(True))

    # 等待对话框关闭
    await dialog
    return result


def _page(page: str = "main"):
    ui_page.clear()
    with ui_page:
        if page == "init":
            init()
        else:
            main()


def 开始比赛(p1, p2, game, start):
    数据.开始比赛(p1, p2, game, start)
    _page()
    ui_快捷键.active = True


async def 重新开始(需要确认=True):
    ui_快捷键.active = False

    if 需要确认 == False:
        数据.重新开始()
        _page("init")
        return

    if await show_confirm("🟠 确定要重新开始比赛吗？"):
        数据.重新开始()
        _page("init")
    else:
        ui_快捷键.active = True


def 下一局():
    数据.下一局()
    _page()


def 交换场地():
    数据.交换场地()
    _page()


def 左边加分():
    数据.左边加分()
    _page()


def 左边减分():
    数据.左边减分()
    _page()


def 右边加分():
    数据.右边加分()
    _page()


def 右边减分():
    数据.右边减分()
    _page()
